package drp.snowbell.part;

import java.lang.reflect.Method;

import weibo.toyger.common.exception.CatchException;
import weibo.toyger.common.util.BaseFieldType;
import weibo.toyger.common.util.ObjectTypeConverter;
import weibo.toyger.common.util.TypeHelper;
import weibo.toyger.core.beans.IEntity;
import weibo.toyger.core.farm.Property;
import weibo.toyger.core.farm.PropertyManager;


public abstract class PartBase implements IPart {

	private IEntity tbean;
	private String parameterString;

	/**
	 * 如果子类里有定义的复杂数据类型,必须重载此函数,进行深度拷贝
	 */
	@Override
	public IPart cloneSkill() {
		IPart ret = null;
		try {
			ret = (IPart) super.clone();
		} catch (CloneNotSupportedException e) {
			CatchException.take(e);
		}
		if (ret == null) {
			// TODO 通过反射来复制
		}
		return ret;
	}

	@Override
	public IEntity getTbean() {
		return tbean;
	}

	@Override
	public void setTbean(IEntity beanEntry) {
		tbean = beanEntry;
	}

	// @Override
	// public String getSkillName() {
	// return this.getClass().getName();
	// }

	@Override
	public Object getValue(Property prop) {
		Method method = PropertyManager.getPropertyGetter(this.getClass(), prop);
		Object value = null;
		try {
			value = method.invoke(this);
		} catch (Exception e) {
			CatchException.take(e);
		}
		return value;
	}

	@Override
	public void setValue(Property prop, Object value) {
		Method setter = PropertyManager.getPropertySetter(this.getClass(), prop);
		Object newValue = value;
		if (value != null) {
			BaseFieldType mytype = TypeHelper.getType(value);
			if (mytype != prop.getValueType()) {
				// 转换类型.非基本类型,不能进行转换
				if (mytype != BaseFieldType.Object) {
					newValue = ObjectTypeConverter.changeType(newValue, prop.getValueType());
				}
			}
		}
		try {
			setter.invoke(this, newValue);
		} catch (Exception e) {
			CatchException.take(e);
		}
	}

	@Override
	public String getParameter() {
		return parameterString;
	}

	@Override
	public void setParameter(String parameterString) {
		this.parameterString = parameterString;
	}

	@Override
	public void onSaveStart() {

	}

	@Override
	public void onSaveEnd() {

	}

	@Override
	public void onLoaded() {

	}
}
